package eScrum.panels;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.ajax.markup.html.form.AjaxButton;
import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.form.validation.EqualPasswordInputValidator;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.apache.wicket.validation.IValidatable;
import org.apache.wicket.validation.IValidator;
import org.apache.wicket.validation.ValidationError;

import eScrum.entities.User;
import eScrum.services.UserService;
import eScrum.utils.EncryptionUtil;


public class ChangePasswordPopUp extends Panel {

	public class PasswordValidator implements IValidator<String> {
		private static final long serialVersionUID = 1L;

		public void validate(IValidatable<String> validatable) {
			String pass = validatable.getValue();
			if (pass.length() < 6 || pass.length() > 15) {
				validatable.error(new ValidationError().setMessage(getString("passwordValidation")));
			}
		}
	}

	private String oldPassword;
	private String newPassword;
	private String confirmPassword;

	private static final long serialVersionUID = 1L;

	@SpringBean
	private UserService userService;

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	private User user;
	private long userId;
	private FeedbackPanel feedbackPanel;

	public ChangePasswordPopUp(String panelid, final long userId) {
		super(panelid);
		this.userId = userId;
		feedbackPanel = new FeedbackPanel("feedback");
		add(feedbackPanel);
		// change password form
		Form<User> changePasswordForm = new Form<User>("changePassword");
		changePasswordForm.setOutputMarkupId(true);
		feedbackPanel.setOutputMarkupId(true);
		// old password
		final TextField<String> oldPasswordTextField = new PasswordTextField("oldPassword", new PropertyModel<String>(this, "oldPassword"));
		// oldPasswordTextField.add(new PasswordValidator());
		changePasswordForm.add(oldPasswordTextField);
		// new password
		final TextField<String> newPasswordTextField = new PasswordTextField("newPassword", new PropertyModel<String>(this, "newPassword"));
		newPasswordTextField.add(new PasswordValidator());
		changePasswordForm.add(newPasswordTextField);
		// confirm password
		final TextField<String> confirmPasswordTextField = new PasswordTextField("confirmPassword", new PropertyModel<String>(this, "confirmPassword"));
		changePasswordForm.add(confirmPasswordTextField);
		changePasswordForm.add(new EqualPasswordInputValidator(newPasswordTextField, confirmPasswordTextField));
		changePasswordForm.add(new AjaxButton("ok", changePasswordForm) {
			private static final long serialVersionUID = 1L;

			@Override
			protected void onSubmit(AjaxRequestTarget target, Form<?> registerForm) {
				try {
					doSubmitUser(target);
				} catch (Exception e) {
					reportUnexpectedException(e);
				}
			}

			@Override
			protected void onError(AjaxRequestTarget target, Form<?> form) {
				target.add(feedbackPanel);
			}
		});

		changePasswordForm.add(new AjaxLink<Void>("cancel") {
			private static final long serialVersionUID = 1L;

			@Override
			public void onClick(AjaxRequestTarget target) {
				target.add(feedbackPanel);
				ModalWindow.closeCurrent(target);
			}
		});
		add(changePasswordForm);
	}

	public void refreshData(AjaxRequestTarget target) {
	}

	private void doSubmitUser(AjaxRequestTarget target) {
		target.add(feedbackPanel);
		try {
			user = userService.findById(userId);
			if (oldPassword == null || oldPassword.equals("")) {
				error(getString("oldPasswordRequired"));
			} else {
				if (EncryptionUtil.crypt(oldPassword).equals(user.getPassword())) {
					if (newPassword != null && confirmPassword != null && newPassword.equals((confirmPassword))) {
						user.setPassword(EncryptionUtil.crypt(newPassword));
						userService.saveOrUpdate(user);
						ModalWindow.closeCurrent(target);
					} else {
						error(getString("newConfirmPasswordsNotEqual"));
					}
				} else {
					error(getString("oldPasswordIncorrect"));
				}
			}
		} catch (Exception e) {
			reportUnexpectedException(e);
		} finally {
			refreshData(target);
		}
	}

	protected void reportUnexpectedException(Exception e) {
		e.printStackTrace();
		error(getString("unexpectedError") + (e.getMessage() == null ? getString("unknown") : e.getMessage()));
	}
}
